<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/02/08
 * Time: 13:29
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\Warehouse;
use app\common\model\WarehouseLocation;
use app\common\model\WarehouseStock;
use app\common\model\WarehouseStockLog;
use app\common\service\product\WarehouseService;
use think\facade\Validate;

/**
 * 库存信息
 * Class Stock
 * @package app\admin\controller\wms
 */
class WstockController extends BaseController
{
    /**
     * 库存列表
     * @return string
     * @date 2021/02/08
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $stock = WarehouseStock::with(['warehouse', 'location'])->order("stock desc");
            $this->search($stock);
            $limit = $this->getPageSize();
            $stock = $stock->paginate($limit);
            $this->assign('is_show_edit', $this->user->hasPermissions('/wms/wstock/save'));
            $this->assign("list", $stock->getCollection());
            $this->assign("page", $stock->render());
            return $this->fetch('lists');
        }
        $this->assign('status', ['否', '是']);
        return $this->fetch('index');
    }

    /**
     * 搜索库存信息
     * @param WarehouseStock $stock
     * @date 2021/02/08
     * @author longli
     */
    private function search($stock)
    {
        $stock->where('warehouse_id', $this->warehouse->warehouse_id);
        $this->searchModel($stock, [
            'eq' => ['status'],
            //'like' => ['sku'],
            'times' => ['create_time'],
        ]);
        if($sku = $this->request->request('sku', '', 'trim'))
        {
            $sku = replaceStr($sku);
            $s = \app\common\model\Product::getSkusBySpu($sku);
            $stock->whereIn('sku', !empty($s) ? $s : $sku);
        }
        // 处理子查询
        $subSel = ['code'];
        $pWhere = [];
        foreach($subSel as $f)
        {
            $text = $this->request->post($f, '', 'trim');
            if(empty($text) && !is_numeric($text)) continue;
            $pWhere[$f] = $text;
        }
        if(!empty($pWhere))
        {
            $stock->where("location_id", "IN", function($query)use($pWhere)
            {
                $query->table(WarehouseLocation::getTable())->where($pWhere)->field("location_id");
            });
        }
    }

    /**
     * 更新库存信息
     * @date 2021/02/09
     * @author longli
     */
    public function save()
    {
        if($this->request->isPost())
        {
            $validate = Validate::make([
                'stock_id'  => 'require',
                'min_stock'  => 'require|egt:0',
                'max_stock' => 'require|egt:0',
            ],[
                'stock_id.require' => '非法请求',
                'min_stock.require' => '预警库存必填',
                'min_stock.egt' => '预警库不能小于0',
                'max_stock.require' => '上限库存必填',
                'max_stock.egt' => '上限库存不能小于0',
            ]);
            $data = $this->request->only(['status', 'min_stock', 'max_stock', 'location_id', 'remark', 'stock_id'], 'post');
            if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
            if($data['max_stock'] < $data['min_stock']) $this->error('上限库存不能小于预警库存');
            if(!isset($data['status'])) $data['status'] = WarehouseStock::IS_NO;
            $code = $this->request->post('code', '', 'trim');
            if($code && $location = WarehouseLocation::get(['code' => $code]))
            {
                if($location->warehouse_id != $this->warehouse->warehouse_id)
                {
                    $this->error("库位【{$code}】不属于【{$location->warehouse->name}】，请重新分配");
                }
                if($location->is_used == WarehouseLocation::IS_YES)
                {
                    $this->error("库位【{$code}】已被 SKU【{$location->stock->sku}】占用，请重新分配");
                }
                $data['location_id'] = $location->location_id;
            }
        }
        else
        {
            $validate = Validate::make([
                'stock_id'  => 'require',
                'status'  => 'require',
            ],[
                'stock_id.require' => '非法请求',
                'status.require' => '状态必填',
            ]);
            $data = $this->request->only(['status', 'stock_id'], 'get');
            if(!$validate->batch()->check($data))$this->error(join(', ', $validate->getError()));
        }
        $store = WarehouseStock::get($data['stock_id']);
        WarehouseService::getInstance()->addStock($store->store, $data)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 显示编辑页面
     * @date 2021/02/09
     * @author longli
     */
    public function add()
    {
        $stockId = $this->request->get('stock_id');
        if(empty($stockId)) $this->error('非法请求');
        $stock = WarehouseStock::get($stockId);
        if(empty($stock)) $this->error('库存信息不存在');
        $this->assign('stock', $stock);
        return $this->fetch('add');
    }

    /**
     * 库存日志
     * @date 2021/02/09
     * @author longli
     */
    public function log()
    {
        if($this->request->isAjax())
        {
            $log = WarehouseStockLog::with(['warehouse', 'operate'])
                ->where('warehouse_id', $this->warehouse->warehouse_id)
                ->order('log_id desc');
            $this->searchModel($log, [
                'eq' => ['ref_sn', 'ref_type', 'type'],
                'times' => ['create_time'],
            ]);
            if($sku = $this->request->request('sku', '', 'trim'))
            {
                $sku = replaceStr($sku);
                $s = \app\common\model\Product::getSkusBySpu($sku);
                $log->whereIn('sku', !empty($s) ? $s : $sku);
            }
            $limit = $this->getPageSize();
            $log = $log->paginate($limit);
            $this->assign("list", $log->getCollection());
            $this->assign("page", $log->render());
            return $this->fetch('log_lists');
        }
        $this->assign('types', WarehouseStockLog::$TYPES);
        $refType = \app\common\status\BaseStatus::$REF_TYPE;
        unset($refType['finance_expend']);
        $this->assign('ref_type', $refType);
        return $this->fetch('log');
    }

    /**
     * 获取指定仓库sku库存信息
     * @date 2021/02/15
     * @author longli
     */
    public function stock_info()
    {
        $wid = $this->request->request('warehouse_id', '', 'trim');
        $sku = $this->request->request('sku', '', 'trim');
        if(empty($wid) || empty($sku)) $this->error('仓库和SKU必传');
        $stock = WarehouseStock::whereIn("warehouse_id", $wid)
            ->whereIn("sku", $sku)
            ->column(['sku', 'price', 'stock', 'lock_stock', 'purchase_stock', 'remark', 'image_url'], 'sku');
        $this->success('', '', $stock);
    }
}